package com.wang.mandkey.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.wang.mandkey.App;
import com.wang.mandkey.R;
import com.wang.mandkey.net.Connecter;
import com.wang.mandkey.net.ConnecterPool;
import com.wang.mandkey.net.INetCallBack;
import com.wang.mandkey.net.IScreenPuller;
import com.wang.mandkey.net.ScreenPuller;
import com.wang.mandkey.tool.RemoteOperateImpl;
import com.wang.mandkey.tool.Tool;
import com.wang.mandkey.utils.ProjectEnvironment;
import com.wang.mandkey.utils.SharePersistent;
import com.wang.mandkey.utils.StringUtils;
import com.wang.mandkey.views.MouseView;

public class MouseActivity extends BaseActivity implements IScreenPuller,
		INetCallBack {

	private MouseView mMouseView;
	private String tag = "MouseActivity";
	private ScreenPuller mScreenPuller = null;

	public View mTableView = null;
	public boolean mBooleanIsAddWindowView = false;
	public boolean mBooleanisStartScreen = false;
	private Button mButtonEnter;
	private Button mButtonClose;
	private Button mButtonRight;
	private Button mButtonOpenScreen;
	private ProgressDialog mProgressDialog;
	private ComputeScreenTask mComputeScreenTask;
	private Connecter mConenctor;
	private int INT_LAYOUT_DO = 0;// 重新设置layout参数
	private WindowManager windowmanager;

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		windowmanager = (WindowManager) (WindowManager) getSystemService(Context.WINDOW_SERVICE);

		setUpView();
		Tool.showWifiStrenth(this);
		mConenctor = ConnecterPool.getConnectorByKey(ConnecterPool.STRING_CKEY);
		if (null == mConenctor) {
			Toast.makeText(this, R.string.mouse_activity_net,
					Toast.LENGTH_SHORT).show();
		} else {
			mMouseView.setRemoteOperateImpl(new RemoteOperateImpl(mConenctor,
					this));
			ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED = true;
		}
		if (isNeedComputeLayoutParam()) {
			mComputeScreenTask = new ComputeScreenTask();
			mComputeScreenTask.execute();
		} else {
			// Log.i(tag, "不需要计算！");
		}

	}

	@Override
	void setUpView() {
		setContentView(R.layout.mouse_view);
		mMouseView = (MouseView) findViewById(R.id.mouseView);
		if (null == ProjectEnvironment.pointHostScreen) {
			Toast.makeText(this, R.string.mouse_activity_net,
					Toast.LENGTH_SHORT).show();
		} else {
			// 如果这个point对象不是kong，说明已经接通了网络，因为接通网络的第一件事情就是把pc机的屏幕高宽度，写入这个值
		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
		return;
	}

	/**
	 * 计算最合适的屏幕比例，保证用户使用方便 void 下午02:28:45 2011
	 */
	public float computeScaleLayoutParam() {
		float scale = -1f;
		int hostx = ProjectEnvironment.pointHostScreen.x;
		int hosty = ProjectEnvironment.pointHostScreen.y;
		int tx = Tool.getDisplayMetrics(this).x;
		// int unvisibleHeight=Tool.geteAppUnVisibleHeight(this);//
		// 在我的平板上这个值竟然是0*/;
		// int ty=Tool.getDisplayMetrics(this).y-unvisibleHeight;
		int ty = Tool.getDisplayMetrics(this).y - 0;// 全屏
		for (float i = 1;;) {
			// 从1倍到无限倍的缩小,知道可以完全可见为止
			float nx = hostx / i;
			float ny = hosty / i;
			if (nx < tx && ny < ty && (ty - ny) > 40) {// 40是一个假设值
				ProjectEnvironment.FLOAT_SCALE = i;
				ProjectEnvironment.INT_AFTER_SCALE_X = (int) nx;
				ProjectEnvironment.INT_AFTER_SCALE_Y = (int) ny;
				setlayoutPram4MouseView();
				scale = i;
				break;
			}
			i = i + 0.01f;
		}
		return scale;
	}

	@Override
	public void onOptionsMenuClosed(Menu menu) {
		hideFakeTitleBar();
		super.onOptionsMenuClosed(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		showFakeTitleBar();
		return super.onMenuOpened(featureId, menu);
	}

	private void hideFakeTitleBar() {
		if (null != mTableView) {
			windowmanager.removeView(mTableView);
			mBooleanIsAddWindowView = false;
		}
	}

	/**
	 * 顶部弹出的工具栏 void 上午11:39:13 2011
	 */
	private void showFakeTitleBar() {
		if (mBooleanIsAddWindowView) {
			return;
		}
		mTableView = View.inflate(this, R.layout.tab_view, null);
		mButtonClose = (Button) mTableView.findViewById(R.id.buttonClose);
		mButtonClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendRemoteCommand(ProjectEnvironment.STRING_COMMAND_CLOSE);
			}
		});

		mButtonEnter = (Button) mTableView.findViewById(R.id.buttonOpen);
		mButtonEnter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				sendRemoteCommand((ProjectEnvironment.STRING_COMMAND_ENTER));
				sendRemoteCommand((ProjectEnvironment.STRING_COMMAND_DOUBLE_CLICK));
			}
		});
		mButtonRight = (Button) mTableView.findViewById(R.id.buttonRight);
		mButtonRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendRemoteCommand(ProjectEnvironment.STRING_COMMAND_RIGHT_CLICK);
			}
		});

		mButtonOpenScreen = (Button) mTableView
				.findViewById(R.id.buttonRemoteScreen);
		if (mBooleanisStartScreen) {
			mButtonOpenScreen.setText(getResources().getString(
					R.string.tab_stop_screen));
		} else {
			mButtonOpenScreen.setText(getResources().getString(
					R.string.tab_start_screen));
		}

		mButtonOpenScreen.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mBooleanisStartScreen == false) {// 如果没有开启，就开启
					mScreenPuller = new ScreenPuller(MouseActivity.this);
					mMouseView.getRemoteOperateImpl().sendCommand(
							ProjectEnvironment.STRING_COMMMAND_START_IMG_SEND);
					mButtonOpenScreen.setText(getResources().getString(
							R.string.tab_stop_screen));
					mBooleanisStartScreen = true;
				} else {// 如果开启了，就关掉
					mMouseView.setmBitmapbackGround(null);
					mScreenPuller.killSelf();
					mMouseView.getRemoteOperateImpl().sendCommand(
							ProjectEnvironment.STRING_COMMAND_STOP_IMG_SEND);
					mButtonOpenScreen.setText(getResources().getString(
							R.string.tab_start_screen));
					mBooleanisStartScreen = false;
				}
				// sendRemoteCommand(ProjectEnvironment.string);
			}
		});

		View view1 = getWindow().peekDecorView();
		android.view.WindowManager.LayoutParams layoutparams = new android.view.WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, -1);
		layoutparams.gravity = 48;
		Rect rect = new Rect();
		view1.getWindowVisibleDisplayFrame(rect);
		int i = rect.top;
		layoutparams.y = i;
		windowmanager.addView(mTableView, layoutparams);
		mBooleanIsAddWindowView = true;
	}

	/**
	 * 当用户选择了当前ItmeSelected
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.menuItemLock:
			ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED = true;
			break;
		case R.id.menuItemExit:
			App.exitApp(this);
			break;
		case R.id.menuItemUnLock:
			ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED = false;
			break;

		default:
			break;
		}
		return false;
	}

	public void sendRemoteCommand(String command) {
		if (ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED) {
			mMouseView.getRemoteOperateImpl().sendCommand(command);
		} else {
			Tool.ToastShow(MouseActivity.this,
					R.string.mouse_activity_lock_first);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_mouse, menu);
		return true;
	}

	/**
	 * 内部handler
	 */
	private Handler mhandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			setlayoutPram4MouseView();
			if (null != mComputeScreenTask) {
				if (mComputeScreenTask.isCancelled() == false) {
					mComputeScreenTask.cancel(true);
				}
			}
		};
	};

	/**
	 * 设置mouseView的layoutparam
	 * 
	 * @param nx
	 * @param ny
	 *            void 下午03:38:43 2011
	 */
	public void setlayoutPram4MouseView() {
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				ProjectEnvironment.INT_AFTER_SCALE_X,
				ProjectEnvironment.INT_AFTER_SCALE_Y);
		mMouseView.setLayoutParams(layoutParams);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (null != mScreenPuller) {
			mScreenPuller.killSelf();
			this.mMouseView.getRemoteOperateImpl().sendCommand(
					ProjectEnvironment.STRING_COMMAND_STOP_IMG_SEND);
			Log.i(tag, "destory");
		}
		if (null != mComputeScreenTask) {
			if (false == mComputeScreenTask.isCancelled())
				mComputeScreenTask.cancel(true);

		}
	}

	@Override
	public void OnFinishPullScreen(Drawable drawable) {
	}

	@Override
	public void OnInterceptedScreen(String tag) {
		if (tag.equals("ScreenPuller")) {
			// 网络端口断掉了
			Log.e(tag, " screen net down");
		}
	}

	@Override
	public void OnStartPullScreen() {

	}

	@Override
	public void OnFinish() {

	}

	@Override
	public void OnIntercepted(String source) {
		Tool.doNetLost(this);
	}

	@Override
	public void OnStart() {

	}

	@Override
	public void OnFinishPullScreenBitmap(Bitmap bitmap) {
		if (null != bitmap) {
			this.mMouseView.setmBitmapbackGround(bitmap);
			// this.mouseView.postInvalidate();
		} else {
			Log.e(tag, "call drawble back is null");
			this.mMouseView.setmBitmapbackGround(null);
		}
	}

	/**
	 * 判断是否重新计算比例
	 * 
	 * @return boolean 下午04:01:47 2011
	 */
	public boolean isNeedComputeLayoutParam() {
		String oldhost = SharePersistent.getPerference(MouseActivity.this,
				STRING_SCREEN_HOST);
		String oldScale = SharePersistent.getPerference(MouseActivity.this,
				STRING_SCALE);
		if (!StringUtils.isEmpty(oldhost) && !StringUtils.isEmpty(oldScale)) {
			if (oldhost.equals(mConenctor.getmStringRemoteHost())) {

				int hostx = ProjectEnvironment.pointHostScreen.x;
				int hosty = ProjectEnvironment.pointHostScreen.y;

				float scalei = Float.parseFloat(oldScale);
				ProjectEnvironment.FLOAT_SCALE = scalei;
				float nx = hostx / scalei;
				float ny = hosty / scalei;

				ProjectEnvironment.INT_AFTER_SCALE_X = (int) nx;
				ProjectEnvironment.INT_AFTER_SCALE_Y = (int) ny;

				mhandler.sendEmptyMessage(INT_LAYOUT_DO);
				Log.i(tag, "use old scale:" + scalei);
				return false;
			} else {
				return true;
			}
		}
		return true;
	}

	/**
	 * 计算缩放比例的asynTask
	 * 
	 * @author wang 下午02:58:13-2011 TODO
	 */
	class ComputeScreenTask extends AsyncTask<Void, Float, Float> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(MouseActivity.this);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setTitle(getResources().getString(
					R.string.mouse_activity_compute));
			mProgressDialog.setCancelable(false);
			mProgressDialog.setMessage(getResources().getString(
					R.string.mouse_activity_compute_scale));
			mProgressDialog.show();
		}

		@Override
		protected Float doInBackground(Void... params) {
			return computeScaleLayoutParam();
		}

		@Override
		protected void onProgressUpdate(Float... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Float result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			SharePersistent.savePerference(MouseActivity.this,
					STRING_SCREEN_HOST, mConenctor.getmStringRemoteHost());
			SharePersistent.savePerference(MouseActivity.this, STRING_SCALE,
					String.valueOf(result));
		}

	}

	private static String STRING_SCREEN_HOST = "sceen_host";
	private static String STRING_SCALE = "screen_scale";
}
